#include "ErrorLogDlg.h"
#include <assert.h>
#include "WndReg.h"

extern CWndReg reg;

#define GRID_CTRL_ID    (1)

CErrorLogDlg::CErrorLogDlg()
{
   m_bVisible = false;
}

LRESULT CErrorLogDlg::OnShowDlg(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   if (!m_bVisible) {
      ShowWindow(SW_SHOW);
      m_bVisible = true;
   }
   return 0;
}

LRESULT CErrorLogDlg::OnHideDlg(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   if (m_bVisible) {
      ShowWindow(SW_HIDE);
      m_bVisible = false;
   }
   return 0;
}

LRESULT CErrorLogDlg::OnDelErrors(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   int nRows = m_ctlGrid.GetRows();
   if (nRows > 1) {
      m_ctlGrid.DeleteRows(1, nRows-1);
   }
   return 0;
}

LRESULT CErrorLogDlg::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   reg.AddWnd(m_hWnd);

   HWND hPlaceHolder = GetDlgItem(IDC_ERRORLOG);
   assert (hPlaceHolder);
   
   RECT rc;
   ::GetWindowRect(hPlaceHolder, &rc);
   ScreenToClient(&rc);

   m_ctlGrid.SetCols(2);
   m_ctlGrid.CreateGridCtrl(m_hWnd, rc, 0, WS_EX_CLIENTEDGE, GRID_CTRL_ID);
   m_ctlGrid.SetString(0, 0, _T("Number"));
   m_ctlGrid.SetString(0, 1, _T("Error"));
   m_ctlGrid.SetColWidth(1, rc.right-rc.left - 85);
   bHandled = TRUE;
   ShowWindow(SW_HIDE);
   return FALSE;
}

LRESULT CErrorLogDlg::OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
   OnDelErrors(0, 0, 0, bHandled);
   OnHideDlg(0, 0, 0, bHandled);
   return 0;
}

#define ERROR_ID_LEN 16
LRESULT CErrorLogDlg::OnAddError(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   LPCTSTR txt = (LPCTSTR) wParam;
   int nRows = m_ctlGrid.GetRows();
   m_ctlGrid.InsertRows(nRows, 1);
   TCHAR tszNumber[ERROR_ID_LEN];
   _sntprintf(tszNumber, ERROR_ID_LEN, "%d", nRows);
   m_ctlGrid.SetString(nRows, 0, tszNumber);
   m_ctlGrid.SetString(nRows, 1, txt);
   return 0;
}

LRESULT CErrorLogDlg::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   return OnHideDlg(0, 0, 0, bHandled);
}
